layui.use(["app", "api", "layer"], function () {
    let app = layui.app
    let api = layui.api
    let layer = layui.layer

    // 监听数据
    
    let data = app.proxy({
        detail: {},
        oldseo: {}
    });

    /**
     * api 渲染
     */
    function render() {
        let id = layui.url().hash.search.id
        console.log(layui.url())
        api.post(
            "/app/kb_blog/api/note/search",
            {
                page: 1,
                limit: 1,
                where: [
                    { key: "id", "value": id }
                ]
            }
        ).then(function (res) {
            if (res.data.data.length <= 0) {
                layer.msg("没有这样的文章", { icon: 2 }, function () {
                    app.navigateTo("note")
                })
            } else {
                data.detail = res.data.data[0]
                seo(data.detail.title,
                    data.detail.keyword,
                    data.detail.description)
                // console.log(data.oldseo)
            }
        })
    }

    /**
     * seo
     * @param {string} title 标题
     * @param {string} keyword 关键词
     * @param {string} description 描述
     */
    function seo(title, keyword, description) {
        document.title = title;
        // 移除旧的 description 元标签
        let oldDescription = document.querySelector('meta[name="description"]');
        if (oldDescription) {
            oldDescription.parentNode.removeChild(oldDescription);
        }

        // 创建并添加新的 description 元标签
        let newDescription = document.createElement('meta');
        newDescription.name = "description";
        newDescription.content = description;
        document.getElementsByTagName('head')[0].appendChild(newDescription);

        // 移除旧的 keyword 元标签
        let oldKeyword = document.querySelector('meta[name="keyword"]');
        if (oldKeyword) {
            oldKeyword.parentNode.removeChild(oldKeyword);
        }

        // 创建并添加新的 keyword 元标签
        let newKeyword = document.createElement('meta');
        newKeyword.name = "keyword";
        newKeyword.content = keyword;
        document.getElementsByTagName('head')[0].appendChild(newKeyword);
    }

    /**
     * 获取seo
     */
    function get_seo() {
        data.oldseo.title = document.title
        let oldKeyword = document.querySelector('meta[name="keyword"]')
        data.oldseo.keyword = oldKeyword.keyword
        let oldDescription = document.querySelector('meta[name="description"]');
        data.oldseo.description = oldDescription.content;
    }

    /**
     * 挂载
     */
    app.onMount = function () {
        get_seo()
        render()
    }

    /**
     * 卸载
     */
    app.onDestroy = function () {
        // console.log("卸载了", data)
        seo(data.oldseo.title,
            data.oldseo.keyword,
            data.oldseo.description)
    }
})